from typing import List, Optional
from sentence_transformers import SentenceTransformer
from utils.base_utils import logger, timer, get_config
import threading

MODEL_NAME = get_config("embedding_model")
_models = {}
_models_lock = threading.Lock()

@timer
def get_embed_model(model_name: str = MODEL_NAME) -> SentenceTransformer:
    if model_name not in _models:
        with _models_lock:
            if model_name not in _models:
                logger.info(f"🧠 加载模型: {model_name}")
                _models[model_name] = SentenceTransformer(model_name)
                logger.info(f"✅ 模型 {model_name} 加载完成")
    return _models[model_name]

@timer
def get_text_embedding(text: str, model_name: Optional[str] = None) -> List[float]:
    model = get_embed_model(model_name or MODEL_NAME)
    if not isinstance(text, str):
        text = str(text)
    text = text.strip()
    try:
        embedding = model.encode(text)
        return embedding.tolist() if hasattr(embedding, "tolist") else list(embedding)
    except Exception as e:
        logger.error(f"❌ 生成嵌入向量时出错: {str(e)}")
        raise RuntimeError(f"Embedding 生成失败: {str(e)}") from e